package vip.indo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.indo.common.JsonResult;
import vip.indo.entity.User;
import vip.indo.service.UserService;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: tianlianyin
 * @Date: 2024/11/28 16:22
 * @Descripition:
 */
@RestController
@RequestMapping("/listener")
@Slf4j
public class ListenerController {
    @Resource
    private UserService userService;
    @GetMapping("/user")
    public JsonResult getUserListener(HttpServletRequest request){
        ServletContext application=request.getServletContext();
        return JsonResult.success(application.getAttribute("user"));
    }

    /**
     * 获取当前在线人数
     * @param request
     * @return
     */
    @GetMapping("/totalUser")
    public JsonResult getTotalUser(HttpServletRequest request, HttpServletResponse response){
        Cookie cookie;
        try {
            //吧sessionId记录在浏览器中
            cookie=new Cookie("JSESSIONID", URLEncoder.encode(request.getSession().getId(),"utf-8"));
            cookie.setPath("/");//设置cookie的路径
            //设置Cookie的有效期，单位是秒，默认是-1，表示关闭浏览器就失效
            cookie.setMaxAge(48*60*60);
            response.addCookie(cookie);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        Integer count= (Integer) request.getSession().getServletContext().getAttribute("count");
        Map<String,Object> map= new HashMap<>();
        map.put("当前在线人数：",count);
        return JsonResult.success(map);
    }
    @GetMapping("/requestInfo")
    public JsonResult getRequestInfo(HttpServletRequest request){
        log.info("requestListener中的初始化的name数据：{}",request.getAttribute("name") );
        return JsonResult.success();
    }
    @GetMapping("/event")
    public JsonResult getRequestEvent(HttpServletRequest request){
        User user=userService.getUserEvent();
        return JsonResult.success(user);
    }
}
